package factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class DaoFactory {
    private static final String daoPackageName = "dao";
    private static final Logger LOGGER = LoggerFactory.getLogger(DaoFactory.class);
    private static final Map<String, Object> daoCache = new HashMap<>();

    private DaoFactory() {}

    public static <T> T getDao(Class<T> daoInterface, String daoClassName) throws RuntimeException {
        String key = daoInterface.getName() + "." + daoClassName;
        if (daoCache.containsKey(key)) {
            return (T) daoCache.get(key);
        }
        try {
            Class<?> clazz = Class.forName(daoPackageName + "." + daoClassName);
            if (!daoInterface.isAssignableFrom(clazz)) {
                throw new RuntimeException("类 " + daoPackageName + "." + daoClassName + " 没有实现接口 " + daoInterface.getName());
            }
            T instance = (T) clazz.newInstance();
            daoCache.put(key, instance);
            return instance;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("在包 " + daoPackageName + " 中找不到DAO类 " + daoClassName, e);
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("在实例化DAO类 " + daoPackageName + "." + daoClassName + " 时发生错误", e);
        }
    }
}
